import json
import re
import subprocess
import jmespath
import ruamel.yaml


def read_yml(file_path, node=None):
    with open(file_path, "r", encoding="utf-8") as f:
        yaml = ruamel.yaml.YAML(typ='unsafe', pure=True)
        yaml.allow_duplicate_keys = True
        data = yaml.load(f)
    if node:
        return data[node]
    else:
        return data if data else []


def write_to_yml(file_path, data):
    # 顺序写入新的yml文件中,保证格式不混乱
    with open(file_path, "w", encoding="utf-8") as f:
        ruamel.yaml.round_trip_dump(data, f, default_flow_style=False, allow_unicode=True)


def check_port_in_use(port, data_containers_list, data_containers_user_relations_list):
    # 定义要执行的命令
    command = f"netstat -an | grep {port}"
    try:
        # 使用subprocess模块执行命令，并获取输出
        # output = subprocess.check_output(command, shell=True, encoding='utf-8')
        output = "tcp        0      0 0.0.0.0:8182            0.0.0.0:*               LISTEN"
        # 如果命令输出不为空，则表示端口正在使用
        data_list = []
        for i in output.splitlines():
            i = re.sub(r'\s+', ',', i).split(",")
            data_list.append(i)
        print(json.dumps(data_list, ensure_ascii=False))
        status_list = jmespath.search("@[*][-1]", data_list)
        if "ESTABLISHED" not in status_list:
            # 没有用户连接了需要释放资源
            container = jmespath.search(f"@[?@[1]==`{port}`][]", data_containers_list)
            if container:
                data_containers_list.remove(container)
                container[-1] = False
                data_containers_list.append(container)
            print(data_containers_list)
            data_line = jmespath.search(f"@[?@[1]==`{container[0]}`][]", data_containers_user_relations_list)
            if data_line:
                data_containers_user_relations_list.remove(data_line)
            return True
        else:
            return False
    except subprocess.CalledProcessError:
        # 如果命令执行出错，则表示端口没有被使用
        return False

    # 如果命令输出为空，则表示端口没有被使用
    return False


def check_port_use_info(port):
    # 定义要执行的命令
    command = f"netstat -an | grep {port}"
    try:
        # 使用subprocess模块执行命令，并获取输出
        output = subprocess.check_output(command, shell=True, encoding='utf-8')
        # 如果命令输出不为空，则表示端口正在使用
        print(output)
        if output:
            return True
    except subprocess.CalledProcessError:
        # 如果命令执行出错，则表示端口没有被使用
        return False

    # 如果命令输出为空，则表示端口没有被使用
    return False


if __name__ == '__main__':
    data_containers_list = read_yml("data_containers_list.yml")
    port_list = jmespath.search("@[*][1]", data_containers_list)
    for port in port_list:
        result = check_port_use_info(port)
        print("使用情况", result)
    port_list=[8222,8223,8224,8225,8226]
    for port in port_list:
        result = check_port_use_info(port)
        print(f"{port}使用情况", result)

# if __name__ == '__main__':
# data_containers_list = read_yml("data_containers_list.yml")
# data_containers_user_relations_list = read_yml("data_containers_user_relations_list.yml")
# port=""
# for i in range(5):
#     result = check_port_in_use(8181 + i,data_containers_list,data_containers_user_relations_list)
#     if result:
#         write_to_yml("data_containers_list.yml", data_containers_list)
#         write_to_yml("data_containers_user_relations_list.yml", data_containers_user_relations_list)
#         port+=f"{8181 + i},"
#     print(data_containers_list)
#
#     # print("使用情况", result)
